//
//  ContectInfoVC.m
//  HxgProject
//
//  Created by hxg on 2018/3/7.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "ContectInfoVC.h"
#import "PersonInfoCell.h"
#import "RelationVC.h"

#import "RDVTabBarController.h"
#import "AuthenService.h"
#import "ContactInfo.h"
#import "ResObject.h"

#import "NSString+Extention.h"
#import <IQKeyboardReturnKeyHandler.h>

@interface ContectInfoVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
    
}
@property (nonatomic, strong) UITableView *contectInfoTableView;

@property (nonatomic, strong) UIButton *submitBtn;

// 配置数据源
@property (nonatomic, strong) NSMutableArray *personDataSource;


@property (nonatomic, strong) NSMutableArray *relationArr;

@end

@implementation ContectInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
}

- (void)setUpUI
{
    self.navigationItem.title = @"联系人认证";

    [self.view addSubview:self.contectInfoTableView];
    [self.contectInfoTableView registerClass:[PersonInfoCell class]
                     forCellReuseIdentifier:@"PersonCell"];
    
    [self.view addSubview:self.submitBtn];
    [_submitBtn setTitle:@"提交认证" forState:UIControlStateNormal];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes])
    {
        _submitBtn.userInteractionEnabled = NO;//交互关闭
        _submitBtn.alpha = 0.4;//透明度
    }
    else
    {
        _submitBtn.userInteractionEnabled = YES;//交互打开
        _submitBtn.alpha = 1;//透明度
    }
    
    
    [_submitBtn makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.contectInfoTableView.mas_bottom).offset(5.0f);
        make.size.mas_equalTo(CGSizeMake(kScreen_Width /3.0f, 70.0f));
    }];
}

-(UITableView *)contectInfoTableView
{
    if (!_contectInfoTableView)
    {
        _contectInfoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, kScreen_Width, kScreen_Height - 44.0f - 80.0f) style:UITableViewStyleGrouped];
        
        _contectInfoTableView.delegate = self;
        _contectInfoTableView.dataSource = self;
        _contectInfoTableView.tableFooterView = [[UIView alloc] init];
    }
    
    return _contectInfoTableView;
}

- (void)submitAction:(UIButton *)submitBtn
{
    
    if (isEmptyString(self.showContact.contactName1)
        || isEmptyString(self.showContact.contactName2))
    {
        [SVProgressHUD showErrorWithStatus:@"联系人内容不能为空!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    if (![NSString valiMobile:self.showContact.contactPhone1]
        || ![NSString valiMobile:self.showContact.contactPhone2])
    {
        [SVProgressHUD showErrorWithStatus:@"手机格式有误!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    if (isEmptyString(self.showContact.vendorPwd))
    {
        [SVProgressHUD showErrorWithStatus:@"运营商密码不能为空!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"加载中..."];
    AuthenService *au = [[AuthenService alloc] init];
    [au saveContacts:self.showContact withCallBack:^(ResObject *res) {
        [SVProgressHUD dismiss];
        if (res.isSuccess)
        {
            [SVProgressHUD showSuccessWithStatus:@"操作成功!"];
            [SVProgressHUD dismissWithDelay:1.0f];
            // 存储认证结果
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:res.errMsg];
            [SVProgressHUD dismissWithDelay:1.0f];
        }
    }];
}


#pragma mark - tableViewDelegate
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    static NSString *identifier = @"PersonCell";
    
     PersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell)
    {
        cell = [[PersonInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.autherNameLbl.text = [self.personDataSource objectAtIndex:indexPath.section][indexPath.row];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.autherContentField.text = self.showContact.contactName1;
        } else if(indexPath.row == 1){
            cell.autherContentField.text = self.showContact.contactPhone1;
        } else
        {
            cell.autherContentLbl.hidden = NO;
            cell.autherContentLbl.text = self.relationArr[indexPath.section];
            cell.autherContentField.hidden = YES;
            
            if (isEmptyString(self.showContact.relation1)) {
                self.showContact.relation1 = @"父母";
                cell.autherContentField.text = @"父母";
            } else {
                cell.autherContentField.text = self.showContact.relation1;
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.autherContentField.text = self.showContact.contactName2;
        } else if(indexPath.row == 1){
            cell.autherContentField.text = self.showContact.contactPhone2;
        } else
        {
            cell.autherContentLbl.hidden = NO;
            cell.autherContentLbl.text = self.relationArr[indexPath.section];
            cell.autherContentField.hidden = YES;
            if (isEmptyString(self.showContact.relation2)) {
                self.showContact.relation2 = @"父母";
                cell.autherContentField.text = @"父母";
            } else {
                cell.autherContentField.text = self.showContact.relation2;
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    else if(indexPath.section == 2)
    {
        cell.autherContentField.placeholder = @"请输入运营商密码";
        cell.autherContentField.text = self.showContact.vendorPwd;
    }
    
    
    cell.autherContentField.delegate = self;
    cell.autherContentField.tag = indexPath.section * 10 + indexPath.row;
    [cell.autherContentField addTarget:self
                                action:@selector(getVal:)
                      forControlEvents:UIControlEventEditingChanged];

    return cell;
}

- (void)getVal:(UITextField *)textField
{
    switch (textField.tag) {
            //第一个section
        case 0:
            NSLog(@"theOldPassword=>%@",textField.text);
            self.showContact.contactName1 = textField.text;
            break;
        case 1:
            NSLog(@"self.theNewPassword=>%@",textField.text);
             self.showContact.contactPhone1 = textField.text;
            break;
        case 2:
            NSLog(@"theTwiceNewPassword=>%@",textField.text);
            self.showContact.relation1 = textField.text;
            break;
            
            //第二个section
        case 0 + 10:
            NSLog(@"theOldPassword=>%@",textField.text);
            self.showContact.contactName2 = textField.text;
            break;
        case 1 + 10:
            NSLog(@"self.theNewPassword=>%@",textField.text);
            self.showContact.contactPhone2 = textField.text;
            break;
        case 2 + 10:
            NSLog(@"theTwiceNewPassword=>%@",textField.text);
            self.showContact.relation2 = textField.text;
            break;
          
            // 第三个section
        case 0 + 20:
            NSLog(@"self.showContact.vendorPwd=>%@",textField.text);
            self.showContact.vendorPwd = textField.text;
            break;
            
        default:
            break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSArray *rowArr = [self.personDataSource objectAtIndex:section];
    
    return rowArr.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2)
    {
        __weak ContectInfoVC *weakSelf = self;
        RelationVC *relationVC = [[RelationVC alloc] init];
        relationVC.relationCallBack = ^(NSString * relationStr) {
            
            NSLog(@"relationStr:%@",relationStr);
            
            if (0 == indexPath.section)
            {
                weakSelf.showContact.relation1 = relationStr;
            }
            else if(1 == indexPath.section)
            {
                weakSelf.showContact.relation2 = relationStr;
            }
            
            [weakSelf.relationArr replaceObjectAtIndex:indexPath.section
                                            withObject:relationStr];
            [weakSelf.contectInfoTableView reloadData];
        };
        
        if (![[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes]) {
            [self.navigationController pushViewController:relationVC
                                                 animated:YES];
        }
    }
}

#pragma mark -

-(NSMutableArray *)relationArr
{
    if (!_relationArr)
    {
        _relationArr = [[NSMutableArray alloc] initWithObjects:@"父母",@"父母", nil];
    }
    return _relationArr;
}

-(NSMutableArray *)personDataSource
{
    if (!_personDataSource)
    {
        NSArray *contect1 = [NSArray arrayWithObjects:@"联系人一",@"联系人号码",@"联系人关系", nil];
        NSArray *contect2 = [NSArray arrayWithObjects:@"联系人二",@"联系人号码",@"联系人关系", nil];
        NSArray *contect3 = [NSArray arrayWithObjects:@"运营商密码", nil];

        _personDataSource = [[NSMutableArray alloc] init];
        [_personDataSource addObject:contect1];
        [_personDataSource addObject:contect2];
        [_personDataSource addObject:contect3];
    }
    return _personDataSource;
}

#pragma mark - getter、setter

- (UIButton *)submitBtn
{
    if (!_submitBtn)
    {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitBtn setBackgroundColor:mainColor];
        [_submitBtn addTarget:self
                       action:@selector(submitAction:)
             forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitBtn;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    
    [super viewWillDisappear:animated];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes])
    {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
